/**
 * Safely parses a JSON string into an object.
 * @param jsonString - The JSON string to parse.
 * @returns The parsed object if successful, otherwise undefined.
 */
export const safeJSONParse = (jsonString: string): object | undefined => {
  if (!jsonString) return undefined;
  try {
    const parsedData = JSON.parse(jsonString);
    return parsedData;
  } catch (error) {
    console.error("JSON parsing error:", error);
    return undefined; // 返回 undefined 表示转换失败
  }
};

/**
 * 编码HTML实体
 * @param htmlString - The string to encode.
 * @returns The encoded string.
 */
export const encodeHTMLEntities = (htmlString: string): string => {
  const entityMap: { [key: string]: string } = {
    "&amp;": "&",
    "&lt;": "<",
    "&gt;": ">",
    "&quot;": '"',
    "&#39;": "'",
    "&apos;": "'",
    "&#x2F;": "/",
  };
  return htmlString.replace(
    /&amp;|&lt;|&gt;|&quot;|&#39;|&#x2F;|&apos;/g,
    s => entityMap[s]
  );
};

/**
 * Decodes HTML entities back to their original characters.
 * @param encodedString - The encoded string to decode.
 * @returns The decoded string.
 */
export const decodeHTMLEntities = (encodedString: string): string => {
  const entityMap: { [key: string]: string } = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&apos;",
    "/": "&#x2F;",
  };
  return encodedString.replace(/&|<|>|"|'|\//g, s => entityMap[s]);
};

/** 实体转义 for 站点地图 */
export const decodeHTMLEntitiesForSitemap = (encodedString: string): string => {
  const entityMap: { [key: string]: string } = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&apos;",
  };
  return encodedString.replace(/&|<|>|"|'/g, s => entityMap[s]);
};

/** 将JS对象转换为FormData */
export const objectToFormData = (obj: Record<string, any>) => {
  const formData = new FormData();
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      formData.append(key, obj[key]);
    }
  }
  return formData;
};

/** 将FormData转换为JS对象 */
export const formDataToObject = (formData: FormData) => {
  const obj: Record<string, any> = {};
  formData.forEach((value, key) => {
    obj[key] = value;
  });
  return obj;
};

/** 数组转树形结构 */
export function array2tree(array: any[], pid: number | string = 0) {
  try {
    const tree: any[] = [];
    array.forEach(item => {
      if (item.pid === pid) {
        const children = array2tree(array, item.id);
        if (children?.length > 0) item.children = children;
        tree.push(item);
      }
    });
    return tree.sort((a, b) => a?.sort - b?.sort);
  } catch (err) {
    console.log("数组转树形结构出错：", err);
    return [];
  }
}

/** 树形结构转数组 */
export function tree2array(tree: any[]) {
  const result = [] as any[];
  const fn = (_tree: any[]) => {
    _tree.forEach(item => {
      if (item.children && item.children.length > 0) {
        fn(item.children);
        delete item.children;
        result.push(item);
      } else {
        result.push(item);
      }
    });
  };
  fn(tree);
  return result;
}
